/*
 * 事件注册中心
 */
class EventBus {
    handlers: any;
    constructor() {
        this.handlers = {};
    }
    on(type: string, fn: Function) {
        if (!this.handlers[type]) {
            this.handlers[type] = [];
        }
        this.handlers[type].push(fn);
        return this;
    }
    off(type: string, fn: Function) {
        let fns = this.handlers[type];
        for (let i = 0; i < fns.length; i++) {
            if (fns[i] == fn) {
                fns.splice(i, 1);
                break;
            }
        }
        return this;
    }
    emit(...args: any[]) {
        let type = args[0];
        let params = [].slice.call(args, 1);
        let fn = this.handlers[type];
        if (!fn) {
            return;
        }
        fn.forEach((item: Function) => {
            item.apply(this, params); //执行函数
        });
        return this;
    }
    once(type: string, fn: Function) {
        let wrap = (...args: any[]) => {
            fn.apply(this, args); //执行事件后删除
            this.off(type, wrap);
        };
        this.on(type, wrap); //再添加上去
        return this;
    }
}

export default EventBus;
